import * as cc from 'cc';
const { ccclass } = cc._decorator;
const PI180 = Math.PI / 180;
@ccclass('TrackingBullet')
export class TrackingBullet extends cc.Component {
    targetNode: cc.Node = null;        //目标节点
    trackRect: cc.Rect = null;         //追踪矩形
    trackPos: cc.Vec3 = null;          //追踪矩形中心点
    speedX: number = 0;                //X轴速度
    speedY: number = 0;                //Y轴速度
    speedA: number = 1.2;                //加速度
    speedM: number = 12;               //速度上限
    init(pos: cc.Vec3, targetNode: cc.Node) {
        this.node.setPosition(pos);
        this.targetNode = targetNode;
        this.trackRect = targetNode.getComponent(cc.UITransform).getBoundingBox();
        this.trackPos = targetNode.position.clone();
    }
    update(deltaTime: number) {
        let pos = this.node.position, targetPos = this.targetNode.position;
        //目标节点的碰撞矩形
        let collideRect = this.targetNode.getComponent(cc.UITransform).getBoundingBox();
        //如果击中目标节点，则爆炸
        if (this.isCollide(collideRect)) {
            this.node.emit('Blast', pos);
            return;
        }
        //如果击中追踪矩形，则将collideRect作为下一个追踪矩形
        if (this.isCollide(this.trackRect)) {
            this.trackRect = collideRect;
            this.trackPos = targetPos.clone();
        }
        //节点angle始终指向目标节点
        this.node.angle = Math.atan2(targetPos.y - pos.y, targetPos.x - pos.x) / PI180;
        //移动方向始终指向追踪矩形中心点
        let radian = Math.atan2(this.trackPos.y - pos.y, this.trackPos.x - pos.x);
        let cos = Math.cos(radian), sin = Math.sin(radian);
        //计算X轴速度、加速度、速度上限
        let speedXA = this.speedA * cos, speedXM = this.speedM * cos;
        this.speedX = cc.clamp(this.speedX + speedXA, -speedXM, speedXM);
        //计算Y轴速度、加速度、速度上限
        let speedYA = this.speedA * sin, speedYM = this.speedM * sin;
        this.speedY = cc.clamp(this.speedY + speedYA, -speedYM, speedYM);
        //根据X轴速度、Y轴速度计算节点坐标
        this.node.setPosition(pos.x + this.speedX, pos.y + this.speedY);
    }
    //判断节点是否与矩形发生碰撞
    isCollide(rect: cc.Rect): boolean {
        let pos = this.node.position, ut = this.node.getComponent(cc.UITransform);
        if (pos.x + ut.width * 0.5 < rect.x) return false;
        if (pos.x > rect.x + rect.width) return false;
        if (pos.y + ut.height * 0.5 < rect.y) return false;
        if (pos.y > rect.y + rect.height) return false;
        return true;
    }
}